<?php
/**
 * JoomlaZend
 * Zend Framework for Joomla
 * Red Black Tree LLC
 *
 *
 * @author rbsolutions (rbsoultions.us@gmail.com)
 * @copyright (c) 2010 Red Black Tree LLC
 * @category JoomlZend
 * @package ComZend_HelloWorld
 * @link http://joomlazend.rbsolutions.us
 * @version $Id:$
 */
defined ('_VALID_MOS') or
    die('Direct Access to this location is not allowed');
/**
 * IndexController
 *
 * Default controller
 *
 *
 * @author rbsolutions (rbsoultions.us@gmail.com)
 * @copyright (c) 2010 Red Black Tree LLC
 * @category JoomlZend
 * @package ComZend_Chimpmail
 */
class Chimpmail_ListsController extends Core_Controller_Action
{
    /**
     * @var string name for the zend module extension
     */
    protected $_ZendModuleName = "Zend Module";
    /**
     * @var string the name of the zend module type
     */
    protected $_moduleName = 'mod_zend';
    /**
     * @var string|NULL api key
     */
    protected $_apiKey=NULL;
    /**
     * @var string|NULL api URL
     */
    protected $_apiUrl=NULL;
    /**
     * @var string|NULL source email
     */
    protected $_sourceEmail = NULL;
    /**
     * @var NULL or MCAPI the mail chimp api class
     */
    protected $_mcApi = NULL;
    /**
     * @var string the title for the current controller
     */
    protected $_title = "Mail Chimp";
    /**
     * createMenu
     *
     * builds the menu options for this controller
     */
    public function createMenu()
    {
        try {
            if($this->_application->isAdmin()) {
                // top menu options
                JToolBarHelper::title($this->view->translate->_($this->_title),'ChimpMail');
                // create the necessary Models
                $mdlExtension = new Model_Components();
                // check for a valid zend_module install
                $ZendModel = $mdlExtension->getModuleByName($this->_ZendModuleName);
                if($ZendModel==NULL) {
                    throw new Exception('The Zend Module is required in addition to ZFJoomla');
                }
            }
        } catch (Exception $ex) {
            echo "Error creating menu:" . $ex->__toString();
        }
    }

    /**
     * init
     * 
     * initilizes the controller
     */
    public function init()
    {
        parent::init();
        if(Zend_Registry::isRegistered('chimpApiKey')) {
           $this->_apiKey = Zend_Registry::get('chimpApiKey');
           $this->_mcApi = new Chimp_MCAPI($this->_apiKey);
           //echo "apiKey:".$this->_apiKey."<br />";
        }
        if(Zend_Registry::isRegistered('chimpApiUrl')) {
           $this->_apiUrl = Zend_Registry::get('chimpApiUrl');
           //echo "apiUrl:".$this->_apiUrl."<br />";
        }
        if(Zend_Registry::isRegistered('chimpSourceEmail')) {
           $this->_sourceEmail = Zend_Registry::get('chimpSourceEmail');
           //echo "sourceEmail".$this->_sourceEmail."<br />";
        }

    }
    /**
     * indexAction
     *
     * Shows Hello World
     */
    public function indexAction()
    {
        $this->view->hello = $this->view->translate->_("Hello World");
    }
    /**
     * subscribeAction
     * 
     * shows the subscribe form
     */
    public function subscribeAction()
    {
        $frm = new Chimpmail_Form_Subscribe();
        // get the module id
        if(isset($this->_addParams) && isset($this->_addParams->id)) {
            $listId = $this->_addParams->id;
            $frm->getElement('listId')->setValue($listId);
        }
        // handle subscription
        if($this->_request->isPost()) {
            if($frm->isValid($_POST)) {
                $mdlSubscription = new Chimpmail_Model_Subscriptions();
                $mdlSubscription->addSubscription($frm->getValues());
                $retVal = $this->_mcApi->listSubscribe(
                            $frm->getValue('list_id'), //list id
                            $frm->getValue('email_address'), //email
                            array() // merge values
                        );
                if($this->_mcApi->errorCode) {
                    if($this->_mcApi->errorCode!=214) {
                        throw new Exception("Unable to load listSubscribe()!!\n code="
                            .$this->_mcApi->errorCode."\n Msg=".$this->_mcApi->errorMessage."\n");
                    } else {
                        $this->view->thank = $this->view->translate->_('You have already subscribed to this list');
                    }
                } else {
                    $this->view->thank = $this->view->translate->_('Thank you for subscribing');
                }
            }
        } else {
            if(isset($this->_addParams) && isset($this->_addParams->list_id)) {
               $frm->getElement('list_id')->setValue($this->_addParams->list_id);
            }
            if(isset($this->_addParams) && isset($this->_addParams->web_id)) {
                $frm->getElement('web_id')->setValue($this->_addParams->web_id);
            }
            if(isset($this->_addParams) && isset($this->_addParams->title)) {
                $frm->getElement('email_address')->setLabel($this->_addParams->title)->setValue('E-mail address');
            }
        }    
        $this->view->form = $frm;
    }
    /**
     * adminindexAction
     * 
     * shows Hello World
     */
    public function adminindexAction() 
    {
        if($this->_application->isAdmin()) {
            // create the menu 
            $this->createMenu();
            $mdlLists = new Chimpmail_Model_Lists();
            $dbLists = $mdlLists->getLists();
            $chimpLists = $this->_mcApi->lists();
            if($this->_mcApi->errorCode) {
                throw new Exception("Error loading lists from Chimpmail:".$this->_mcApi->errorCode." ". $this->_mcApi->errorMessage);
            } else {
                // fill in the lists where they do not exist
                foreach($chimpLists['data'] as $cList) {
                    $dbList = $mdlLists->getChimpList($cList['id']);
                    if($dbList==NULL) {
                        $mdlLists->addList(array(
                            'list_id'=>$cList['id'],
                            'web_id'=>$cList['web_id'],
                            'name'=>$cList['name'],
                        ));
                    }
                }
            }
            $this->view->lists = $mdlLists->getLists();

        }
    }
    /**
     * subscribersAction
     * 
     * shows a list of the subscribed users
     */
    public function subscribersAction()
    {
        if($this->_application->isAdmin()) {
            // top menu options
            JToolBarHelper::title($this->view->translate->_($this->_title),'ChimpMail');
        }
    }
    /**
     * modulesAction
     * 
     * shows the modules associated with the provided list
     */
    public function modulesAction()
    {
        if($this->_application->isAdmin()) {
            // create the menu 
            $this->createMenu();
            $mdlLists = new Chimpmail_Model_Lists();
            if(isset($this->_addParams) && isset($this->_addParams->list_id)) {
                $id = $this->_addParams->list_id;
            } else {
                throw new Exception("Error, invalid list id provided");
            }
            if(isset($this->_addParams) && isset($this->_addParams->web_id)) {
                $webId = $this->_addParams->web_id;
            } else {
                throw new Exception("Error, invalid web id provided");
            }
            $mdlModules = new Model_Modules();
            $modules = $mdlModules->getModules($this->_title);
            // ensure at least one module exists
            if($modules == NULL) {
                // a module does not exist so create one
                $mdlModules->addModule(
                    $this->_title, // title
                    '', // note
                    '', // content
                    'user1', // position
                    $this->_moduleName, //module
                    1, // access
                    1, // showtitle 
                    array(
                        'zmodule'=>$this->_module,
                        'zcontroller'=>$this->_name,
                        'zaction'=>'subscribe',
                        'addparams'=>  json_encode(array(
                            'title'=>$this->_title,
                            'list_id'=>$id,
                            'web_id'=>$webId,
                        )),
                    ), // params 
                    0 // client_id
                );
                $modules = $mdlModules->getModules($this->_title);
            }
            $moduleArray = array();
            foreach($modules as $module) {
                $params = json_decode($module->params);
                if(isset($params->addparams)) {
                    $addParams = json_decode($params->addparams);
                    if(isset($addParams->list_id)&&isset($addParams->web_id)) {
                        if($addParams->list_id == $id && $addParams->web_id == $webId) {
                            $moduleArray[] = $module;
                        }
                    }
                }
            }
            // no modules found, add one
            if(sizeof($moduleArray)<=0) {
                $mdlModules->addModule(
                    $this->_title, // title
                    '', // note
                    '', // content
                    'user1', // position
                    $this->_moduleName, //module
                    1, // access
                    1, // showtitle 
                    array(
                        'zmodule'=>$this->_module,
                        'zcontroller'=>$this->_name,
                        'zaction'=>'subscribe',
                        'addparams'=>  json_encode(array(
                            'title'=>$this->_title,
                            'list_id'=>$id,
                            'web_id'=>$webId,
                        )),
                    ), // params 
                    0 // client_id
                );
            }
            $this->view->modules = $moduleArray;
        }        
    }
}